package org.summerframework.component.mybites.redis;

import org.summerframework.component.mybites.config.MybatisConfiguration;
import org.summerframework.core.util.SpringContextUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.cache.decorators.LoggingCache;
import org.springframework.data.redis.core.RedisTemplate;


/**
 * @author shichao
 */
public class LoggingRedisCache extends LoggingCache {

    private static String redisId = "";
    private static RedisTemplate<String, Object> redisTemplate;

    static {
        if (StringUtils.isBlank(redisId)) {
            LoggingRedisCache.setRedisId(SpringContextUtil.getBean(MybatisConfiguration.MyBatisRedisProperties.class).getId());
        }
    }

    public LoggingRedisCache(String id) {
        super(new RedisMybatisCache(id, redisTemplate));
    }

    public static void setRedisId(String redisId) {
        if (redisId != null) {
            LoggingRedisCache.redisId = redisId;
        }
    }

    public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        LoggingRedisCache.redisTemplate = redisTemplate;
    }

    public static String getRedisId(String id) {
        return (StringUtils.isNotBlank(redisId) ? redisId + ":" : "") + id.replace(".", ":");
    }

    public static void clean(String id) {
        redisTemplate.delete(getRedisId(id));
    }
}
